/**
 * @file	common.c
 * @author	chipsea
 * @brief	
 * @version	0.1
 * @date	2020-11-30
 * @copyright Copyright (c) 2020, CHIPSEA Co., Ltd.
 * @note
 */
#include "sdk_config.h"
#include "global_config.h"
#include "OSAL_Tasks.h"
#include "rf_phy_driver.h"
#include "pwrmgr.h"
#include "gpio.h"
#include "timer.h"
#include "uart.h"
#include "log.h"
#include "common.h"
#include "spi.h"

//__asm uint32_t get_msp_addr()
//{
//    mrs r0, msp;
//    bx lr;// cppcheck-suppress missingReturn
//}

//__STATIC_FORCEINLINE uint32_t get_msp_addr(void)
//{
//	return __get_MSP();
//}

#define DUMP_LOG
#ifdef DUMP_LOG
unsigned int cur_sp;
unsigned int sp_data[16];

void Dump_Record(void)
{
    cur_sp = __current_sp();
    
    for(int i = 0; i< 0x10; i++)
    {
        sp_data[i] = ((uint32_t*)cur_sp)[i];
	}
    LOG("DUMP LOG V1\r\n");
    LOG("Hard Fault SP is %x\n",cur_sp);
    LOG("crash fun:0x%x\r\n", sp_data[9]);
    LOG("crash addr:0x%x\r\n", sp_data[12]);
    for(int i = 0; i< 0x10; i++)
    {
        LOG("crash data:0x%x\r\n", sp_data[i]);
	}
}
#endif
void hard_fault(void)
{
#ifdef DUMP_LOG
    Dump_Record();
#endif
	while(1);
}

__ATTR_SECTION_XIP__ uint32_t osal_memory_statics(uint32 memTotalSize)
{
    osalMemHdr_t *header, *current;
    void *ptr;
    uint32  sum_alloc = 0;

    ptr = (void *)(g_largeHeap);

    header = (osalMemHdr_t *)ptr;
    current = (osalMemHdr_t *)ptr;
    
    HAL_ENTER_CRITICAL_SECTION();  // Hold off interrupts.
	
    do
    {     
        if ((uint32)ptr >= (uint32)header + memTotalSize)
        {
            break;
        }      

        // seek to the last block, return
        if ( current->val == 0 )       /// val = 0, so len = 0
        {
            break;
        }
        
        if (current->hdr.inUse)
		{
            sum_alloc += current->hdr.len;
		}
        current = (osalMemHdr_t *)((uint8 *)current + current->hdr.len);    
    } while (1);

    HAL_EXIT_CRITICAL_SECTION();  // Re-enable interrupts. 
	return sum_alloc;
}

#ifdef DBG_SPI_USE
void dbg_spi_init(AP_SSI_TypeDef* SPIx)
{
	spi_Cfg_t cfg;
    
    cfg.ssn_pin = P31;
	cfg.sclk_pin = P32;
	cfg.MISO = GPIO_DUMMY;
	cfg.MOSI = P33;
	cfg.baudrate = 12000000;
    cfg.spi_tmod = SPI_TRXD;
	cfg.spi_scmod = SPI_MODE0;
	cfg.spi_dfsmod = SPI_1BYTE;
    cfg.dma_rx_enable = false;
    cfg.dma_tx_enable = false;
	cfg.int_mode = false;
	cfg.evt_handler = NULL;
	cfg.force_cs = false;
    cfg.is_slave = false;
	HalSpiMasterConfig(SPIx, &cfg);
}
void dbg_spi_out_buf(uint8_t connId, uint8_t *buf, uint8_t len)
{
	AP_SPI1->DataReg=0xA0+connId;

	while(len--)
	{
		AP_SPI1->DataReg = *buf++;
	}
}
#endif
